<template>
    <div class="echart-root">
        <BaseEchart ref="baseEchartRef" :options="configRpe" :style="{ height: data.style.height }">
        </BaseEchart>
    </div>
</template>

<script setup lang="js">
import { ref, watch } from 'vue'
import { fetchCardBody } from '@/api/global'
import { useGlobalStore } from '@/store/global'
import { storeToRefs } from 'pinia'

const props = defineProps({
    searchForm: { // 卡片查询表单
        type: Object,
        default: () => ({})
    },
    // 针对于echart
    data: {
        default: () => ({
            cardId: "", //卡片id
            type: "", // 类型 echart/table
            url: "", // 接口地址
            style: {}, // 卡片主体样式
            config: {}, // 卡片配置
        })
    }
})

// baseEchart dom
const baseEchartRef = ref(null)

const globalStore = useGlobalStore()

const { globalSearchForm } = storeToRefs(globalStore)

// 统一处理 鼠标移入echart 样式
props.data.config.tooltip = {
    ...(props.data.config.tooltip || {}),
    backgroundColor: "rgba(0,0,0,0.7)",
    borderColor: "rgba(0,0,0,0.7)",
    textStyle: {
        color: "#fff"
    }
};

// 图表配置项
const configRpe = ref(props.data.config)

// 初始化数据
const initData = async () => {
    // configRpe.value.dataset.dimensions = ["name", "value", "percentage"]
    // configRpe.value.dataset.source = [
    // { name: "测试1", value: 10, percentage: 10 },
    // { name: "测试2", value: 20, percentage: 20 },
    // { name: "测试3", value: 70, percentage: 70 },
    // { name: "测试4", value: 50, percentage: 50 },
    // ]
    const mergedForm = {
        ...props.searchForm,
        ...globalSearchForm.value
    }
    // 发送请求
    const res = await fetchCardBody(props.data.url, mergedForm)
}

// 监听左上角 区域 以及 日期时间 卡片自带查询条件
watch(
    [() => globalSearchForm.value, () => props.searchForm],
    ([globalForm, localForm]) => {
        const mergedForm = { ...localForm, ...globalForm }
        if (Object.keys(mergedForm).length !== 0) {
            initData()
        }
    },
    { deep: true } // 需要深度监听
)

// 下载图表
const downloadImage = () => {
    return baseEchartRef.value?.getEchartImage()
}

defineExpose({ downloadImage })
</script>
<style scoped lang="scss">
.echart-root {
    margin-top: vh(10);
}
</style>